import React, { RefObject } from "react";
import { Form, Input, Button, Radio, Toast } from "antd-mobile";
import request from "../../api/request";
import { rsaEncrypt } from "../../hooks/Jsencrypt";
import Navbar from "../../compounts/navber/Navbar";
import { UserOutline, LockFill } from "antd-mobile-icons";
import style from './login.module.css'
import { useNavigate } from "react-router-dom";
import { saveUserData } from "../../utils/tokenManager";

function Index() {
    const nav = useNavigate()
    // 登录表单
    const onFinish = async (values) => {
        console.log(values);
        try {
            const pwd = rsaEncrypt(values.pwd);
            const params = new URLSearchParams();
            params.append("email", values.email);
            params.append("pwd", pwd);

            // 使用正确的API路径，添加/health前缀
            const response = await request.post("/health/user/v1/login", params, {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
            });
            console.log(response);
            if (response.data.status === "0000") {
                Toast.show({
                    content: '登录成功',
                    duration: 2000,
                });
                
                // 保存完整的用户数据
                const userData = {
                    token: response.data.result.token || 'mock-token-' + Date.now(),
                    userId: response.data.result.userId || response.data.result.id || 'user-' + Date.now(),
                    email: values.email,
                    headPic: response.data.result.headPic
                };
                
                saveUserData(userData);
                
                // 触发自定义事件，通知其他页面用户数据已更新
                window.dispatchEvent(new CustomEvent('userDataChanged'));
                
                // 跳转页面
                nav('/home')
            } else {
                Toast.show({
                    content: `登录失败: ${response.data.message}`,
                    duration: 2000,
                });
            }
        } catch (e) {
            console.error("登录失败:", e.response ? e.response.data : e.message);
            Toast.show({
                content: "登录失败，请稍后重试",
                duration: 2000,
            });
        }
    };
    return (
        <div className={style.box}>
            <Navbar title={'登录'}></Navbar>
            <div className={style.title}>人民健康通行证</div>
            <Form
                layout="horizontal"
                onFinish={onFinish}
                requiredMarkStyle='none'
                footer={
                    <Button block type="submit" shape='rounded' color="primary" size="large" style={{ marginTop: '30px' }}>
                        提交
                    </Button>
                }
            >
                {/* 账号 */}
                <Form.Item
                    name="email"
                    label={<UserOutline style={{ color: '#f55a55' }} />}
                    rules={[{ required: true, message: "姓名不能为空" }]}
                    style={{ '--prefix-width': '40px', textAlign: 'center', fontSize: '20px' }}
                >
                    <Input placeholder="请输入邮箱号" />
                </Form.Item>
                {/* 密码 */}
                <Form.Item
                    name="pwd"
                    label={<LockFill style={{ color: '#f55a55' }} />}
                    rules={[{ required: true, message: "密码不能为空" }]}
                    style={{ '--prefix-width': '40px', textAlign: 'center', fontSize: '20px' }}
                >
                    <Input placeholder="请输入密码" />
                </Form.Item>

                <div className={style.radiobox}>
                    <Radio>登录即同意《服务协议》和 《隐私政策》</Radio>
                </div>
            </Form>
            <div className={style.loginBtn}>密码登录</div>
        </div>
    );
}

export default Index;
